package com.douyu.data.rabbitmq.work.round;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerWork2 {

    public static Runnable consumer = new Runnable() {

        @Override
        public void run() {
//        1. 创建连接工程
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("172.22.34.1"); // 172.22.34.1
            connectionFactory.setPort(5672);
            connectionFactory.setUsername("admin");
            connectionFactory.setPassword("admin");
            connectionFactory.setVirtualHost("healerVH");
            Connection connection = null;
            Channel channel = null;
            String queueName = Thread.currentThread().getName();
            try {
//            2. 创建连接Connection
                connection = connectionFactory.newConnection("生产者");
                //        3. 通过连接获取通道Channel
                channel = connection.createChannel();
                Channel finalChannel = channel;
                finalChannel.basicConsume(queueName, true, new DeliverCallback() {
                    @Override
                    public void handle(String consumerTag, Delivery message) throws IOException {
                        System.out.println(queueName + ": " + new String(message.getBody(), "UTF-8"));
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }, new CancelCallback() {
                    @Override
                    public void handle(String consumerTag) throws IOException {
                        System.out.println("卧槽，无情");
                    }
                });
                System.out.println(queueName + "开始接收消息");
                System.in.read();
            }catch (Exception e){

            } finally {
//        7. 关闭通道
                if(channel != null && channel.isOpen()){
                    try {
                        channel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (TimeoutException e) {
                        e.printStackTrace();
                    }
                }
//        8. 关闭连接
                if(connection != null && connection.isOpen()){
                    try {
                        connection.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    public static void main(String[] args) {
        String[] method = {"wechat", "qq", "sms", "email","healerQueue"};
        for (String s : method) {
            new Thread(consumer, s).start();
        }
    }
}
